package com.mirror.tk.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.mirror.tk.core.module.sys.domain.SysAttachment;
import com.mirror.tk.core.module.sys.service.SysAttachmentService;
import com.mirror.tk.framework.common.dao.support.PageInfo;
import com.mirror.tk.framework.utils.mapper.JsonMapper;
import com.mirror.tk.web.common.support.SessionFace;
import com.mirror.tk.web.common.support.SessionUser;

@Controller
@RequestMapping("global/upload")
public class AttachmentControler extends CommonController {

	@Resource
	private SysAttachmentService attachmentService;

	@RequestMapping(value = "save")
	// @ResponseBody
	public String upload(HttpServletRequest request, HttpServletResponse response) {
		SessionUser su = SessionFace.getSessionUser(request);
		//Long userId = su.getId();
		Long userId = 1l;
		String sysKey = "sys";
		logger.debug("referer:{}", request.getHeader("referer"));
		if (request.getHeader("referer") != null && request.getHeader("referer").indexOf("/module/restaurant") != -1) {
			//userId = SessionFace.getBranchUserId(request);
			sysKey = "restaurant";
		}

		
		CommonsMultipartResolver mutilpartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		SysAttachment attach = null;
		// request如果是Multipart类型、
		if (mutilpartResolver.isMultipart(request)) {
			// 强转成 MultipartHttpServletRequest
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取MultipartFile类型文件
			Iterator<String> it = multiRequest.getFileNames();
			if (it != null && it.hasNext()) {
				MultipartFile fileDetail = multiRequest.getFile(it.next());
				if (fileDetail != null) {
					attach = attachmentService.upload(userId, sysKey, "", fileDetail);
				}
			}
		}
		if (attach == null) {
			return null;
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("url", attach.getAttachUrl());
		map.put("filename", attach.getAttachUrl());
		StringBuffer strBuff = new StringBuffer("<script>").append("window.parent.uploaderImageComplete(").append(JsonMapper.nonEmptyMapper().toJson(map)).append(");").append("</script>");
		try {
			response.getWriter().print(strBuff.toString());
		} catch (IOException e) {
			logger.error("file upload error", e);
		}
		return null;
	}

	@RequestMapping(value = "delete")
	@ResponseBody
	public String list(HttpServletRequest request, @RequestParam(value = "url", required = false) String url) {
		logger.debug("referer:{}", request.getHeader("referer"));
		try {
			attachmentService.delete(url);
			return "success";
		} catch (Exception e) {
			return "";
		}
	}

	@RequestMapping(value = "list")
	public String list(HttpServletRequest request, 
			@RequestParam(value = "callback", required = false) String callback, 
			@RequestParam(value = "options", required = false) String opts,
			Map<String, Object> map) {
		SessionUser su = SessionFace.getSessionUser(request);
		Long userId = 1l;
		String sysKey = "sys";
		logger.debug("referer:{}", request.getHeader("referer"));
		if (request.getHeader("referer") != null && request.getHeader("referer").indexOf("/module/restaurant") != -1) {
			//userId = SessionFace.getBranchUserId(request);
			sysKey = "restaurant";
		}

		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Boolean> sortMap = new HashMap<String, Boolean>();
		searchMap.put("EQ_userId", userId);
		searchMap.put("EQ_sysKey", sysKey);
		sortMap.put("createTime", false);
		PageInfo pageInfo = new PageInfo(24, 1);
		pageInfo = attachmentService.query(pageInfo, searchMap, sortMap);
		map.put("list", pageInfo.getPageResults());
		map.put("callback", callback);
		map.put("url", opts);

		return "common/file_browser";
	}

	@RequestMapping(value = "ajax/list")
	public String ajaxList(HttpServletRequest request,
			@RequestParam(value = "callback", required = false) String callback,
			@RequestParam(value = "options", required = false) String opts,
			Map<String, Object> map) {
		SessionUser su = SessionFace.getSessionUser(request);
		Long userId = 1l;
		String sysKey = "sys";
		logger.debug("referer:{}", request.getHeader("referer"));
		if (request.getHeader("referer") != null && request.getHeader("referer").indexOf("/module/restaurant") != -1) {
			//userId = SessionFace.getBranchUserId(request);
			sysKey = "restaurant";
		}

		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Boolean> sortMap = new HashMap<String, Boolean>();
		searchMap.put("EQ_userId", userId);
		searchMap.put("EQ_sysKey", sysKey);
		sortMap.put("createTime", false);

		PageInfo<SysAttachment> pageInfo = attachmentService.query(getPageInfo(request, 24), searchMap, sortMap);
		map.put("list", pageInfo.getPageResults());
		map.put("callback", callback);
		map.put("url", opts);

		return "common/image_waterfall";
	}
	
}
